package com.product.shopping.controller;

import com.product.shopping.Rabbit.ServerBizException;
import com.product.shopping.entity.Product;
import com.product.shopping.service.ProductService;
import org.apache.tomcat.util.http.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * (Product)表控制层
 *
 * @author makejava
 * @since 2020-03-10 23:34:05
 */
@RestController
@RequestMapping("product")
public class ProductController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private ExecutorService product = new ThreadPoolExecutor(10,15,60 * 3,
                                     TimeUnit.SECONDS,new SynchronousQueue<>());
    /**
     * 服务对象
     */
    @Resource
    private ProductService productService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Product selectOne( @RequestParam Integer id) {
        return this.productService.queryById(id);
    }
    /**
     * 秒杀入口
     * @param Pid-商品id，做检查库存使用
     * @param Pnum-用户id，做订单和用户关联使用（比如生成成功秒杀商品的用户订单表）
     * 			     我这里没做多余的逻辑，只看了相关情况的返回结果，有需要的可以自己去实现
     */
    @RequestMapping(value = "secondsKill", method = RequestMethod.POST)
    public void secondsKill(String Pid, Integer Pnum) {

        //模拟发送100次请求，库存设置为少于100查看结果，此100次请求为顺序请求（未并发）
        //for (int i = 0 ;i<100 ;i++) {
            //product.submit(()->{
                boolean result = false;
                try {
                    result = productService.secondsKill(Pid, String.valueOf(Pnum));
                } catch (ServerBizException e) {
                    e.printStackTrace();
                }
                if (result){
                    logger.info("成功");
                }
            //});
        //}
    }
}
